package com.bkhech.netty.utils;

import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.dialect.PropsUtil;
import cn.hutool.system.SystemUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * PropertiesUtil
 *
 * @author guowm
 * @date 2024-11-20
 */
public class PropertiesUtil {
    private static final String CHAT_MESSAGE_PROPERTIES_PATH = "chat-message.properties";
    private static final String CHAT_MESSAGE_PROPERTIES_PATH_PROD = "chat-message-prod.properties";

    private static volatile Props INSTANCE;

    private PropertiesUtil() {
    }

    public static Props getInstance() {
        if (INSTANCE == null) {
            synchronized (PropertiesUtil.class) {
                if (INSTANCE == null) {
                    String chatMessagePropPath = CHAT_MESSAGE_PROPERTIES_PATH;
                    final String profile = SystemUtil.get("PROFILE");
                    if ("prod".equals(profile)) {
                        chatMessagePropPath = CHAT_MESSAGE_PROPERTIES_PATH_PROD;
                    }
                    // 使用 hutool 工具类读取文件
                    INSTANCE = PropsUtil.get(chatMessagePropPath);
                }
            }
        }

        return INSTANCE;
    }

    /**
     * 获取默认服务器端口
     * @return
     */
    public static int getDefaultPort() {
        return getInstance().getInt("server.defaultPort");
    }

    private static void loadPropertiesFile(Properties properties) {
        InputStream inputStream = PropertiesUtil.class.getResourceAsStream(CHAT_MESSAGE_PROPERTIES_PATH);

        //*.properties配置文件，要使用UTF-8编码，否则会现中文乱码问题
        assert inputStream != null;
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            properties.load(bf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
